import matplotlib.pylab as plt
import numpy as np
from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import train_test_split

x=np.array([[182],[178],[170],[168],[165],[162],[158],[154],[149],[144]])
y=np.array([[113],[105],[86],[83],[86],[74],[72],[45],[49],[43]])
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=0)

k_range=range(2,8)
k_error=[]
#验证最优的k值
for k in k_range:
    model=KNeighborsRegressor(n_neighbors=k)
    model.fit(x_train,y_train)
    scores=model.score(x_test,y_test)
    k_error.append(1-scores)

plt.rcParams['font.sans-serif']='Simhei'
#plt.plot(k_range,k_error,'r-')
#plt.xlabel('k的取值')
#plt.ylabel('预测误差率')
#plt.show()
#得到结论，当k=3时误差率最低
model=KNeighborsRegressor(3)
model.fit(x_train,y_train)

plt.xlabel('身高/cm')
plt.ylabel('体重/kg')
plt.axis([140,190,40,140]) 
plt.scatter(x,y,s=60,c='k',marker='o')		#绘制散点图
plt.plot(x,model.predict(x),'r-')		#绘制曲线
plt.show()


pred=model.predict([[173]])
print(f"身高173cm的学生体重预测为:{pred[0][0]:.2f}")
